package afcp.alumni.action.page;

import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.security.Secure;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;
import afcp.alumni.action.base.PageAction;
import afcp.alumni.model.db.Member;
import afcp.alumni.security.PasswordEncoder;
import afcp.alumni.service.impl.MemberServiceImpl;

@UrlBinding(value = ChangePasswordAction.URL)
@Secure(roles = PageAction.VISIBLE)
public class ChangePasswordAction extends PageAction {

	@Override
	public String getTitle() {
		return msg("changepassword.title");
	}

	@Override
	protected String defaultJsp() {
		return JSP;
	}

	@Override
	public String getUrl() {
		return URL;
	}

	@Override
	public Resolution view() {
		return toJsp();
	}

	public static final String URL = "/changepassword";
	private static final String JSP = "/WEB-INF/jsp/changepassword.jsp";
	public static final String FROM_PARAM = "from";

	@SpringBean
	private MemberServiceImpl memberService;
	
	@Validate(on="changePassword", required=true, minlength=6)
	private String newPassword;
	@Validate(on="changePassword", required=true)
	private String newPassword2;
	
	private String from;

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public void setNewPassword2(String newPassword2) {
		this.newPassword2 = newPassword2;
	}

	@ValidationMethod(on = "changePassword")
	public void validateNewPassword(ValidationErrors errors) {
		if (!newPassword.equals(newPassword2)) {
			errors.add("newPassword2",
					new LocalizableError("myspace.mustbesame"));
		} else if (context.getUser().getPassword()
				.equals(PasswordEncoder.hash(newPassword))) {
			errors.add("newPassword", new LocalizableError(
					"changepassword.mustbedifferent"));
		}
	}
	
	public Resolution changePassword() {
		Member user = context.getUser();
		user.setPassword(newPassword);
		user.setPasswordChanged(true);
		memberService.addOrUpdateMember(user);
		addFlashScope("myspace.changepassword.ok");
		if (from != null) {
			return new RedirectResolution(from);
		} else {
			return new RedirectResolution(HomeAction.class);
		}
	}

}
